import { Component, PropsWithChildren } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtButton, AtIcon, AtTag } from 'taro-ui'
import Taro from '@tarojs/taro'
import './index.scss'
import { getFoodList, calculateStatus } from '../../services/foodService'

interface FoodItem {
  id: string
  name: string
  category: string
  quantity: number
  unit: string
  purchaseDate: string
  expiryDate: string
  status: 'normal' | 'low' | 'expiring'
  location?: string
  image?: string
}

interface State {
  expiringFoods: FoodItem[]
  lowStockFoods: FoodItem[]
}

export default class ExpiryWarning extends Component<PropsWithChildren, State> {
  constructor(props: PropsWithChildren) {
    super(props)
    this.state = {
      expiringFoods: [],
      lowStockFoods: []
    }
  }

  componentDidMount() {
    this.loadWarningFoods()
  }

  loadWarningFoods = () => {
    const allFoods = getFoodList()
    const expiringFoods: FoodItem[] = []
    const lowStockFoods: FoodItem[] = []

    allFoods.forEach(food => {
      const status = calculateStatus(food.expiryDate)
      const updatedFood = { ...food, status }
      
      if (status === 'expiring') {
        expiringFoods.push(updatedFood)
      } else if (status === 'low') {
        lowStockFoods.push(updatedFood)
      }
    })

    // 按过期时间排序，最快过期的在前面
    expiringFoods.sort((a, b) => new Date(a.expiryDate).getTime() - new Date(b.expiryDate).getTime())
    lowStockFoods.sort((a, b) => new Date(a.expiryDate).getTime() - new Date(b.expiryDate).getTime())

    this.setState({ expiringFoods, lowStockFoods })
  }

  handleGoBack = () => {
    Taro.navigateBack()
  }

  handleGoToKitchen = () => {
    Taro.navigateTo({
      url: '/pages/kitchen/index'
    })
  }

  getCategoryIcon = (category: string) => {
    switch (category) {
      case '蔬菜': return '🥬'
      case '主食': return '🍚'
      case '肉类': return '🥩'
      case '水果': return '🍎'
      case '蛋奶': return '🥚'
      case '调料': return '🧂'
      default: return '🍱'
    }
  }

  getDaysUntilExpiry = (expiryDate: string) => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const expiry = new Date(expiryDate)
    expiry.setHours(0, 0, 0, 0)
    const diffTime = expiry.getTime() - today.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  }

  getExpiryText = (expiryDate: string) => {
    const days = this.getDaysUntilExpiry(expiryDate)
    if (days < 0) {
      return `已过期 ${Math.abs(days)} 天`
    } else if (days === 0) {
      return '今天过期'
    } else if (days === 1) {
      return '明天过期'
    } else {
      return `${days} 天后过期`
    }
  }

  render() {
    const { expiringFoods, lowStockFoods } = this.state
    const totalWarningItems = expiringFoods.length + lowStockFoods.length

    return (
      <View className='expiry-warning-page'>
        {/* 顶部导航栏 */}
        <View className='top-navbar'>
          <View className='navbar-left'>
            <AtIcon 
              value='chevron-left' 
              size='24' 
              className='back-icon'
              onClick={this.handleGoBack}
            />
            <Text className='page-title'>食材预警</Text>
          </View>
          <View className='navbar-right'>
            <AtIcon 
              value='home' 
              size='20' 
              className='nav-icon'
              onClick={this.handleGoToKitchen}
            />
          </View>
        </View>

        {/* 预警概览 */}

        <ScrollView className='warning-content' scrollY>
          {/* 即将过期食材 */}
          {expiringFoods.length > 0 && (
            <View className='warning-section'>
              <View className='section-header'>
                <View className='section-icon'>🚨</View>
                <View className='section-info'>
                  <Text className='section-title'>即将过期</Text>
                  <Text className='section-subtitle'>{expiringFoods.length} 种食材需要尽快使用</Text>
                </View>
              </View>
              
              <View className='food-cards'>
                {expiringFoods.map(food => (
                  <View key={food.id} className='warning-food-card expiring'>
                    <View className='card-header'>
                      <View className='food-basic-info'>
                        <Text className='food-emoji'>{this.getCategoryIcon(food.category)}</Text>
                        <View className='food-text-info'>
                          <Text className='food-name'>{food.name}</Text>
                          <Text className='food-category'>{food.category}</Text>
                        </View>
                      </View>
                      <AtTag 
                        type='primary' 
                        size='small' 
                        className='expiry-tag expiring'
                      >
                        {this.getExpiryText(food.expiryDate)}
                      </AtTag>
                    </View>
                    
                    <View className='card-details'>
                      <View className='detail-item'>
                        <AtIcon value='map-pin' size='14' />
                        <Text className='detail-text'>{food.location || '冷藏一层'}</Text>
                      </View>
                      <View className='detail-item'>
                        <AtIcon value='shopping-bag' size='14' />
                        <Text className='detail-text'>{food.quantity} {food.unit}</Text>
                      </View>
                      <View className='detail-item'>
                        <AtIcon value='calendar' size='14' />
                        <Text className='detail-text'>过期日期: {food.expiryDate}</Text>
                      </View>
                    </View>
                  </View>
                ))}
              </View>
            </View>
          )}

          {/* 低库存食材 */}
          {lowStockFoods.length > 0 && (
            <View className='warning-section'>
              <View className='section-header'>
                <View className='section-icon'>⚠️</View>
                <View className='section-info'>
                  <Text className='section-title'>需要关注</Text>
                  <Text className='section-subtitle'>{lowStockFoods.length} 种食材一周内过期</Text>
                </View>
              </View>
              
              <View className='food-cards'>
                {lowStockFoods.map(food => (
                  <View key={food.id} className='warning-food-card low'>
                    <View className='card-header'>
                      <View className='food-basic-info'>
                        <Text className='food-emoji'>{this.getCategoryIcon(food.category)}</Text>
                        <View className='food-text-info'>
                          <Text className='food-name'>{food.name}</Text>
                          <Text className='food-category'>{food.category}</Text>
                        </View>
                      </View>
                      <AtTag 
                        type='primary' 
                        size='small' 
                        className='expiry-tag low'
                      >
                        {this.getExpiryText(food.expiryDate)}
                      </AtTag>
                    </View>
                    
                    <View className='card-details'>
                      <View className='detail-item'>
                        <AtIcon value='map-pin' size='14' />
                        <Text className='detail-text'>{food.location || '冷藏一层'}</Text>
                      </View>
                      <View className='detail-item'>
                        <AtIcon value='shopping-bag' size='14' />
                        <Text className='detail-text'>{food.quantity} {food.unit}</Text>
                      </View>
                      <View className='detail-item'>
                        <AtIcon value='calendar' size='14' />
                        <Text className='detail-text'>过期日期: {food.expiryDate}</Text>
                      </View>
                    </View>
                  </View>
                ))}
              </View>
            </View>
          )}

          {/* 无预警食材时的提示 */}
          {totalWarningItems === 0 && (
            <View className='no-warning'>
              <View className='no-warning-icon'>🎉</View>
              <Text className='no-warning-title'>太棒了！</Text>
              <Text className='no-warning-subtitle'>目前没有需要特别关注的食材</Text>
              
              <AtButton 
                type='primary'
                className='back-to-kitchen-btn'
                onClick={this.handleGoToKitchen}
              >
                返回厨房管理
              </AtButton>
            </View>
          )}
        </ScrollView>

        {/* 底部操作栏 */}
        {totalWarningItems > 0 && (
          <View className='bottom-actions'>
            <AtButton 
              type='primary'
              className='bottom-action-btn'
              onClick={this.handleGoToKitchen}
            >
              去厨房管理
            </AtButton>
            <AtButton 
              className='bottom-action-btn secondary'
              onClick={() => {
                Taro.showToast({
                  title: '功能开发中',
                  icon: 'none'
                })
              }}
            >
              制定使用计划
            </AtButton>
          </View>
        )}
      </View>
    )
  }
}
